package com.zzyl.intercept;

import com.zzyl.constant.JwtConstants;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.HttpStatus;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/6/9 16:52
 * @Version: 1.0
 */
@Slf4j
@Service
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取header种的token，key：authorization
        String token = request.getHeader(JwtConstants.TOKEN_KEY);
        //判断token是否为空
        if (StringUtils.isEmpty(token)) {
            //如果token是空，返回401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        //如果token不是空
        //解析token
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getBase64EncodedSecretKey(), token);
            //如果解析token成功，获取token中的memberId
            Long memberId = claims.get(JwtConstants.MEMBER_ID, Long.class);
            if (memberId == null || memberId <= 0) {
                response.setStatus(HttpStatus.UNAUTHORIZED);
                return false;
            } else {
                //把memberId保存到ThreadLocal
                UserThreadLocal.set(memberId);
                log.info("保存用户id到TL：{}", memberId);
                return true;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
